package org.jeecg.common.filter;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author lixingxing
 */
@Slf4j
public class HttpServletRequestNullParametersWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = null;

    private byte[] bytes;

    public HttpServletRequestNullParametersWrapper(HttpServletRequest request) throws IOException {
        super(request);
        params = Maps.newHashMap(request.getParameterMap());
        List<String> keys = Lists.newArrayList();
        //移除 "" "undefined" "null"的请求参数
        String[] empty = {"undefined", "null"};
        params.forEach((key, values) -> {
            if (StringUtils.isBlank(values[0]) || ArrayUtil.contains(empty, values[0])) {
                keys.add(key);
            }
        });
        for (String key : keys) {
            params.remove(key);
        }
        bytes = IoUtil.readBytes(request.getInputStream());
        if (!isValidJson(bytes)) {
            Object obj = JSON.parse(bytes);
            bytes = JSON.toJSONBytes(obj);
        }
    }

    /**
     * 判断字符串是否是合法json
     *
     * @param bytes
     * @return
     */
    private boolean isValidJson(byte[] bytes) {
        try {
            JSON.parse(bytes);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        return ArrayUtil.isEmpty(values) ? null : values[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return params;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = params.get(name);
        return values;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream buffer = new ByteArrayInputStream(bytes);
        ServletInputStream stream = new ServletInputStream() {

            @Override
            public int read() {
                return buffer.read();
            }

            @Override
            public boolean isFinished() {
                return buffer.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

        };
        return stream;
    }
}
